/**
* require PreferenceStringContainer.js
*/ 

function WhiteListContainer() {
	this.construct();
}

WhiteListContainer.prototype = {
	defaultWhiteList	:	Array(
                                  Array("*.taobao.com", "include"), 
								  Array("*.tmall.com", "include"), 
								  Array("*.etao.com", "include"),
								  Array("*.alimama.com", "include"),								  
								  Array("*.simba.com", "include"),
								  Array("*.daily.taobao.net", "include"),
								  Array("*.daily.etao.net", "include"),
								  Array("*.alimama.net", "include"),
								  Array("acookie.taobao.com", "exclude"),
								  Array("www.atpanel.com", "exclude"),
								  Array("a.tbcdn.cn", "exclude")
							),
	whiteLists	:	Array(),
	
	construct:	function(){
		//如果preference中的whitelist为空，存入一个默认值
		this.getWhiteList();
		if(this.whiteLists == "") {
			this.whiteLists = this.defaultWhiteList;
			preferenceStringContainer.setStrings(this.whiteLists, "whitelist");
		}
    },
	
	reset: function(mywindow){
		this.whiteLists = this.defaultWhiteList;
		if(confirm("确认重置为默认项")){
			preferenceStringContainer.setStrings(this.whiteLists, "whitelist");
			this.flush(mywindow);
		}
		mywindow.focus();
		return true;
	},
	
	getWhiteList:	function() {
		this.whiteLists = preferenceStringContainer.getStrings("whitelist");
	},

	addWhiteList:	function(hostWhiteList, type, mywindow){
		if(!hostWhiteList){
            return false;
        }
        
        if(this.checkUniq(hostWhiteList)){
			this.whiteLists.push(Array(hostWhiteList, type));
			preferenceStringContainer.setStrings(this.whiteLists, "whitelist");
			this.flush(mywindow);
            return true;
        }
        else{
            return false;
        }
	},
	
	addWhiteLists:	function(mywindow){
		var tree = mywindow.document.getElementById("xssUrl");
		if(tree.currentIndex == -1) return;
		var selection = tree.view.selection;
		var url = tree.view.getCellText(tree.currentIndex, tree.columns.getColumnAt(0));
		var hostReg = new RegExp("https?://(.*?)/.*","i");		
		if(matches = url.match(hostReg)) {
			host = matches[1];
			
			var uniq = this.checkUniq(host);
			if(uniq == -1) 
				this.whiteLists.push(Array(host, "exclude"));
			else {
				this.whiteLists.splice(uniq, 1);
				this.whiteLists.push(Array(host, "exclude"));
			}
			preferenceStringContainer.setStrings(this.whiteLists, "whitelist");
			this.flush(mywindow);
			alert(host + "已加入域名黑名单");
		}
		else alert("操作失败");
		mywindow.focus();
	},
	
	removeWhiteList:	function(mywindow){
		var tree = mywindow.document.getElementById("whiteListTree");
		this.whiteLists.splice(tree.currentIndex,1); 
		preferenceStringContainer.setStrings(this.whiteLists, "whitelist");
		this.flush(mywindow);
	},
	
	checkUniq:	function(string){
		for(var i=0;i<this.whiteLists.length;i++){
			if(this.whiteLists[i][0] == string)
				return i;
		}
		return -1;
	},

	importWhiteLists:	function(mywindow){
	    var nsIFilePicker = Components.interfaces.nsIFilePicker;
        var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
        picker.init(window, "Select File To Import From", nsIFilePicker.modeOpen);
        picker.appendFilter("All Files", '*');
        var resultOfPicker = picker.show();
        if (resultOfPicker == nsIFilePicker.returnCancel){
            return false;
        }
        var importFile = picker.file;
		var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                                .createInstance(Components.interfaces.nsIFileInputStream);
        var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
					  .createInstance(Components.interfaces.nsIScriptableInputStream);
		istream.init(importFile, 0x01, 0444, 0);
		sstream.init(istream);
        
		//有没有readline的...
		data = "";
		str = sstream.read(4096);
        while (str.length > 0) {
          data += str;
          str = sstream.read(4096);
        }

        istream.close();
		sstream.close();
		
		lines = data.split("\r\n");
		for(i=0; i<lines.length; i++){
			arr = lines[i].split("\t");
			this.whiteLists.push(Array(arr[0], arr[1]));
		}
		preferenceStringContainer.setStrings(this.whiteLists, "whitelist");
		this.flush(mywindow);
	},
	
	exportWhiteLists:	function(mywindow){
		var nsIFilePicker = Components.interfaces.nsIFilePicker;
		var picker = Components.classes['@mozilla.org/filepicker;1'].createInstance(nsIFilePicker);		
        picker.init(mywindow, "Select File To Export To", nsIFilePicker.modeSave);
        picker.appendFilter("All Files", '*');
		
		var resultOfPicker = picker.show();
        if (resultOfPicker == nsIFilePicker.returnCancel){
            return false;
        }
        var exportFile = picker.file;

        var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
                .createInstance(Components.interfaces.nsIFileOutputStream);
		
		foStream.init(exportFile, 0x02 | 0x08 | 0x20, 0666, 0); // write, create, truncate
		
		for(i=0; i<this.whiteLists.length-1; i++){
			line = this.whiteLists[i][0] + "\t" + this.whiteLists[i][1] + "\r\n";
			foStream.write(line, line.length);
		}
		//最后一行不加换行
		line = this.whiteLists[i][0] + "\t" + this.whiteLists[i][1];
		foStream.write(line, line.length);
        foStream.close();
    },


	flush:	function(mywindow){
		this.getWhiteList();
	
		var treechildren = mywindow.document.getElementById("existingWhitelist");

		while(treechildren.childNodes.length>0){		
			treechildren.removeChild(treechildren.childNodes[0]);
		}

		for(var i=0;i<this.whiteLists.length;i++){		
			var treeitem = mywindow.document.createElement("treeitem");
			var row = mywindow.document.createElement("treerow");
			
			var cell = mywindow.document.createElement('treecell');
			cell.setAttribute("label",this.whiteLists[i][0]);
			row.appendChild(cell);
			
			var cell = mywindow.document.createElement('treecell');
			if(this.whiteLists[i][1] == "exclude")
				label = "黑名单";
			else if(this.whiteLists[i][1] == "include")
				label = "白名单";
			cell.setAttribute("label", label);
			row.appendChild(cell);
			
			treeitem.appendChild(row);
			treechildren.appendChild(treeitem);
		}
	}
};
